package com.example.demo.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.answers.entity.TAnswers;
import com.example.demo.answers.service.ITAnswersService;
import com.example.demo.questions.entity.TQuestions;
import com.example.demo.questions.service.ITQuestionsService;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhongZheng
 */
@RestController
@RequestMapping("/export")
public class ExportUtils {

    @GetMapping("/exportJson")
    public String exportJson() {
        List<String> resultList = new ArrayList<>();
        ITQuestionsService questionsService = SpringBeanUtil.getBean(ITQuestionsService.class);
        ITAnswersService answersService = SpringBeanUtil.getBean(ITAnswersService.class);
        QueryWrapper<TQuestions> questionsQueryWrapper = new QueryWrapper<>();
        List<TQuestions> list = questionsService.list(questionsQueryWrapper);
        Gson gson = new Gson();
        list.stream().parallel().forEach(question -> {
            QueryWrapper<TAnswers> answersQueryWrapper = new QueryWrapper<>();
            answersQueryWrapper.eq("QUESTION_ID", question.getId());
            List<TAnswers> answers = answersService.list(answersQueryWrapper);
            question.setAnswers(answers);
            resultList.add(gson.toJson(question));
        });
        return StringUtils.join(resultList.toArray(), "");
    }
}
